import { onMounted, ref, onUnmounted } from 'vue';
import { getAccountResult, accountingModel } from '@/apis/pcf/myModel/modelDetail';
import {
  ICalcResult,
  IValidListItem,
  IStageListItem
} from '@/apis/pcf/myModel/model/modelDetailModel';
import { AccountTypeEnum } from '@/constants/enum';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import { getDqrResult } from '@/apis/pcf/myModel/dqr';
import type { IDqrResult } from '@/apis/pcf/myModel/model/modelDqr';
export const useCalc = (modelNo: string) => {
  const dqrInfo = ref<IDqrResult>({} as IDqrResult);

  const getDqr = async () => {
    try {
      const data = await getDqrResult(modelNo as string);
      dqrInfo.value = data;
    } catch (error) {
      console.log('error', error);
    }
  };
  const loading = ref(false);
  const computeLoading = ref(false);
  const accountStatus = ref<keyof typeof AccountTypeEnum>('NOT_ACCOUNT');
  const timerCount = ref(1);
  const validList = ref<IValidListItem[]>([]);
  const stageList = ref<IStageListItem[]>([]);
  const stageListDataSource = ref<string[]>([]); // 用来更新数据
  const resultDetail = ref({} as ICalcResult);
  const loadData = async () => {
    loading.value = true;
    try {
      const data = await getAccountResult(modelNo);
      validList.value = data.validList ?? [];
      accountStatus.value = data.accountStatus;
      if (accountStatus.value == AccountTypeEnum.ACCOUNTED) {
        getDqr();
      }
      stageList.value = data.stageList ?? [];
      stageListDataSource.value = [data.accountTime];
      resultDetail.value = data;
      // TODO: 临时赋值，接口回传后删除
      resultDetail.value.dqr = 1;
      resultDetail.value.uncertainty = 0.001;
      checkStatus();
    } finally {
      loading.value = false;
    }
  };
  const handleCalc = async () => {
    //
    // 核算碳排结果
    computeLoading.value = true;
    try {
      await accountingModel(modelNo);
      loadData();
    } finally {
      computeLoading.value = false;
    }
  };
  let isWaiting = false; // 是否等待中

  /**
   *  启动定时器
   */
  let timer: any;
  const startInterval = () => {
    timer = setInterval(async () => {
      if (timerCount.value == 200) {
        // 如果超过30秒，直接返回失败并关闭定时器
        accountStatus.value = AccountTypeEnum.FAIL;
        timerCount.value = 1;
        stopInterval();
      } else {
        // 如果不在等待中，触发一次请求，否则则关闭定时器
        if (!isWaiting) {
          isWaiting = true;
          try {
            const data = await getAccountResult(modelNo);
            accountStatus.value = data.accountStatus;
            isWaiting = false;
            if (data.accountStatus !== AccountTypeEnum.RUNNING) {
              validList.value = data.validList;
              stageList.value = data.stageList ?? [];
              resultDetail.value = data;
              stageListDataSource.value = [data.accountTime];
              console.log('timer', data.accountStatus, timerCount.value);
              timerCount.value = 1;
              stopInterval();
            } else {
              timerCount.value++;
              console.log('fetchTimer', 500 * timerCount.value);
            }
          } catch {
            //如果请求失败重新初始化
            accountStatus.value == AccountTypeEnum.FAIL;
            timerCount.value = 1;
            stopInterval();
          }
        } else {
          // stopInterval();
        }
      }
    }, 500 * timerCount.value);
  };

  const stopInterval = () => {
    clearInterval(timer);
    timer = null;
  };

  const checkStatus = () => {
    if (accountStatus.value == AccountTypeEnum.RUNNING) {
      clearInterval(timer);
      timerCount.value = 1;
      startInterval();
    } else if (accountStatus.value == AccountTypeEnum.NOT_ACCOUNT) {
      handleCalc();
    } else {
      clearInterval(timer);
      timerCount.value = 1;
    }
  };
  // 销毁定时器及监听
  function handleDestroy() {
    clearInterval(timer);
    timerCount.value = 1;
    document.removeEventListener('visibilitychange', visibilitychangeHandler);
  }
  document.addEventListener('visibilitychange', visibilitychangeHandler);
  function visibilitychangeHandler(e: Event) {
    if (!document.hidden) {
      loadData();
    }
  }
  onUnmounted(() => {
    handleDestroy();
  });
  onMounted(() => {
    loadData();
  });
  useKeepAliveRefresh(loadData);

  return {
    handleCalc,
    validList,
    stageList,
    resultDetail,
    loading,
    accountStatus,
    stageListDataSource,
    dqrInfo
  };
};
